<template>
  <div class="toolIcon">
    <!--地图标注对话框-->
    <map-calibration v-if="dialogMapCalibrationVisible" :dialogVisible="dialogMapCalibrationVisible" @closeDialog="closeMapCalibrationDialog" :position="mapCalibrationPoint" @addMarker="addMarker" @spliceObjlist="spliceObjlist">
    </map-calibration>
    <!--选择分组对话框-->
    <choose-group v-if="dialogChooseGroupVisible" :dialogVisible="dialogChooseGroupVisible" @closeDialog="closeChooseGroupDialog" @searchByDrawType="searchByDrawType">
    </choose-group>
    <!-- 保存快照弹窗 -->
    <el-dialog width="30%" title="描述信息" :visible.sync="photoVisible" class="saveKz">
      <el-form>
        <el-form-item label="描述信息">
          <el-input v-model="description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="photoVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePhoto" v-if="kz_xz">确 定</el-button>
        <el-button type="primary" @click="editSnapData()" v-else>确 定</el-button>
      </div>
    </el-dialog>
    <div id="Markmenu" :class="!MarkmenuShow?'nodata':''">
      <li @click="removeMarker()">移除</li>
      <li @click="selecthandleAddGroup()">添加到该分组</li>
    </div>
  </div>
</template>
<script>
import { getGisList, saveMapSnapshot, getMapSnapshot } from '@/api/map'
import util from '@/utils'
import { addInstance, snapshot, getdetail } from '@/api/relationFraph'
import mapUtil from '@/utils/mapUtil'
import gmapUtil from '@/utils/gmapUtil'
import eventPointImg from '@/images/event-point.png'
import eventPointCheckImg from '@/images/event-point-checked.png'
const MapCalibration = () => import('@/views/map/map-calibration.vue')
const ChooseGroup = () => import('@/views/map/choose-group.vue')
export default {
    data () {
        return {
            // 打点图片
            eventPointImg: eventPointImg,
            eventPointCheckImg: eventPointCheckImg,
            // 绘画类型
            drawType: '',
            // 地图打标点对象
            drawingManagerMarker: '',
            // 画矩形对象
            drawingManagerRectangle: '',
            // 画多边形对象
            drawingManagerPolygon: '',
            // 画圆对象
            drawingManagerCircle: '',
            // 画线对象
            drawingManagerPolyline: '',
            // 地图标注对话框
            dialogMapCalibrationVisible: false,
            // 选择分组对话框
            dialogChooseGroupVisible: false,
            // 地图打点标注的经纬度
            mapCalibrationPoint: {},
            current_checked_marker: {},
            // 对象列表
            objectList: [],
            // 地图上点的集合
            markerListNew: this.markerList ? this.markerList : [],
            // 事件管理器
            EventWrapper: '',
            // 被选中的标点
            objectInfo: {},
            // 页面上的所有点覆盖物
            allMark: [],
            // 描述信息弹窗
            photoVisible: false,
            // 描述信息
            description: '',
            // 当前选择快照id
            currentSnapId: '',
            // 是编辑还是新建
            kz_xz: true,
            MarkmenuShow: false,
            // 当前需要删除的marker
            CurrentDelmarker: {},
            // 当前选择快照的索引
            currentBJIndex: -1,
            // 图像绘画变量
            drawingManager: '',
            newMarker: null
        }
    },
    components: {
        MapCalibration,
        ChooseGroup
    },
    props: ['map', 'markerList'],
    created () {},
    watch: {
        map (val) {
            if (val) {
                this.drawingManager = new google.maps.drawing.DrawingManager()
                // 添加监听事件
                google.maps.event.addListener(this.drawingManager, 'markercomplete', this.markercomplete)
                google.maps.event.addListener(this.drawingManager, 'rectanglecomplete', this.rectanglecomplete)
                google.maps.event.addListener(this.drawingManager, 'polygoncomplete', this.polygoncomplete)
                google.maps.event.addListener(this.drawingManager, 'polylinecomplete', this.polylinecomplete)
                google.maps.event.addListener(this.drawingManager, 'circlecomplete', this.circlecomplete)
                // // 添加鼠标绘制工具监听事件，用于获取绘制结果
                // this.EventWrapper = BMapLib.EventWrapper
            }
        }
    },
    mounted () {},
    methods: {
    // 编辑快照
        editSnapData () {
            snapshot(
                JSON.stringify({
                    // snapshot: this.editId,
                    caseId: sessionStorage.getItem('MapgroupId')
                        ? sessionStorage.getItem('MapgroupId')
                        : 1,
                    // graphData: JSON.stringify(graph),
                    id: this.currentSnapId,
                    description: this.description
                })
            )
                .then(data => {
                    this.photoVisible = false
                    this.$message.success('编辑快照成功')
                    this.$parent.handleGetSnapshot(this.currentBJIndex)
                })
                .catch(error => {
                    this.$message.error(error)
                })
        },
        // 快照
        savePhoto () {
            let params = {
                caseId: sessionStorage.getItem('MapgroupId'),
                snapshot: '',
                graphData: JSON.stringify(this.markerListNew),
                description: this.description
            }
            saveMapSnapshot(params).then(res => {
                if (res.status == 200) {
                    this.photoVisible = false
                    this.$message.success('保存快照成功')
                    this.clearOverlays()
                    this.$parent.handleGetSnapshot(0)
                    this.$parent.$refs.timeLine.KZactiveIndex = 0
                }
            })
        },
        // 展示保存快照
        showPhoto () {
            this.photoVisible = true
            this.description = ''
            this.kz_xz = true
        },
        // 设置地图类型
        setMapType (type) {
            if (type === 'normal') {
                this.map.setMapType(BMAP_NORMAL_MAP)
            } else {
                this.map.setMapType(BMAP_SATELLITE_MAP)
            }
        },
        // 初始状态
        initStatus () {
            if (this.drawingManager) {
                this.drawingManager.setOptions(gmapUtil.nullOptions(this.map))
            }
            // this.drawingManager.setMap(null)
        },
        // 获取详情
        getallDetails (params) {
            return new Promise((resolve, reject) => {
                let vm = this
                getdetail(params).then(
                    res => {
                        if (res.status == 200) {
                            resolve(res.data.propertyList)
                        } else {
                            reject([])
                        }
                    },
                    error => {
                        reject(error)
                    }
                )
            })
        },
        // 绘画
        draw (type, event) {
            this.initStatus()
            this.drawType = type
            switch (type) {
            case 'marker':
                this.drawingManager.setOptions(gmapUtil.markerOptions(this.map))
                break
            case 'polygon':
                this.drawingManager.setOptions(gmapUtil.polygonOptions(this.map))
                break
            case 'circle':
                this.drawingManager.setOptions(gmapUtil.circleOptions(this.map))
                break
            case 'polyline':
                this.drawingManager.setOptions(gmapUtil.polylineOptions(this.map))
                break
            case 'rectangle':
                this.drawingManager.setOptions(gmapUtil.rectangleOptions(this.map))
            default:
        // this.drawingManagerRectangle.open()
            }
        },
        // todo
        removeallOverlay (overlay) {
            var allOverlay = this.map.getOverlays()
            for (let item of allOverlay) {
                if (!item.customData) {
                    this.map.removeOverlay(item)
                }
            }
        },
        // 画点完成后，派发的事件接口
        markercomplete (overlay) {
            // this.allMark.push(overlay)
            this.newMarker = overlay
            this.mapCalibrationPoint = {
                lat: overlay.position.lat(),
                lng: overlay.position.lng()
            }
            this.dialogMapCalibrationVisible = true
        },
        // 绘制矩形完成后，派发的事件接口
        rectanglecomplete (overlay) {
            // 关闭绘制矩形
            this.initStatus()
            this.pointArr = []
            let lt = {
                longitude: overlay.bounds.ia.j,
                latitude: overlay.bounds.na.l
            }
            let lb = {
                longitude: overlay.bounds.ia.j,
                latitude: overlay.bounds.na.j
            }
            let rt = {
                longitude: overlay.bounds.ia.l,
                latitude: overlay.bounds.na.l
            }
            let rb = {
                longitude: overlay.bounds.ia.l,
                latitude: overlay.bounds.na.j
            }
            this.pointArr.push(lt, lb, rt, rb)
            console.log(this.pointArr)
            google.maps.event.addListener(overlay, 'click', e => {
                overlay.setMap(null)
                this.dialogChooseGroupVisible = true
            })
        },
        // 绘制多边形完成后，派发的事件接口
        polygoncomplete (overlay) {
            console.log(overlay)
            this.drawingManager.setOptions(gmapUtil.nullOptions())
            this.pointArr = overlay.getPath().j.map(v => {
                return {
                    longitude: v.lng(),
                    latitude: v.lat()
                }
            })
            google.maps.event.addListener(overlay, 'click', e => {
                overlay.setMap(null)
                this.dialogChooseGroupVisible = true
            })
        },
        // 绘制线完成后，派发的事件接口
        polylinecomplete (overlay) {
            this.pointArr = overlay.getPath().j.map(v => {
                return {
                    longitude: v.lng(),
                    latitude: v.lat()
                }
            })
            // let points = overlay.getPath()
            // this.pointArr = this.getlintnewpoint(points)
            console.log(this.pointArr)
            overlay.setMap(null)
            this.dialogChooseGroupVisible = true
        },
        circlecomplete (event) {
            // 关闭绘制圆
            this.drawingManager.setOptions(gmapUtil.nullOptions())
            console.log(event.radius, event.center.lat(), event.center.lng())
            // 获取半径,单位米
            let radius = event.radius
            this.radius = (radius / 1000).toFixed(2)
            this.centerPoint = {
                lat: event.center.lat(),
                lng: event.center.lng()
            }
            google.maps.event.addListener(event, 'click', e => {
                // this.removeallOverlay()
                event.setMap(null)
                this.dialogChooseGroupVisible = true
            })
        },
        // 地图标定成功后拼接对象列表
        spliceObjlist (rowkey, objectUri, objectType, displayName, name, iconUrl) {
            this.objectList = []
            this.objectList.push({
                rowkey: rowkey,
                objectUri: objectUri,
                objectType: objectType,
                displayName: displayName,
                name: name,
                iconUrl: iconUrl,
                longitude: this.mapCalibrationPoint.lng,
                latitude: this.mapCalibrationPoint.lat
            })
        },
        // 去重
        uniq (array) {
            var temp = [] // 一个新的临时数组
            var resultArry = []
            for (var i = 0; i < array.length; i++) {
                if (temp.indexOf(array[i].rowkey) == -1) {
                    temp.push(array[i].rowkey)
                    resultArry.push(array[i])
                }
            }
            return resultArry
        },
        // 添加标注
        addMarker (
            lng,
            lat,
            rowkey,
            objectUri,
            objectType,
            displayName,
            name,
            iconUrl
        ) {
            // 判断是否有经纬度
            if (lng && lat) {
            } else {
                this.$message.error('无经纬度,不可添加哦')
                return false
            }
            // 判断当前需要加入的对象在页面上是否存在
            if (this.markerListNew && this.markerListNew.length > 0) {
                for (let item of this.markerListNew) {
                    if (item.rowkey == rowkey) {
                        // this.$message.error("不可重复添加");
                        return
                    }
                }
            }
            let marker = new google.maps.Marker({
                position: { lat: lat, lng: lng },
                title: displayName,
                icon: process.env.NODE_ENV === 'production' ? '../../dist/static/img/marker_red.png' : '../../static/img/marker_red.png'
            })
            marker.setMap(this.map)
            // let marker = mapUtil.tool.createMarker(new BMap.Point(lng, lat), this.eventPointImg)
            //   this.map.addOverlay(marker);
            // for(var i=0; i < txtMenuItem.length; i++){
            //     markerMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
            // }
            // 点添加右击
            // marker.addContextMenu(markerMenu)
            // 添加自定义属性
            marker.customData = { rowkey: rowkey }
            // 移除map的监听事件
            this.removeMapAllListeners()
            // 将标注添加到标注列表中
            this.markerListNew.push({
                longitude: lng,
                latitude: lat,
                rowkey: rowkey,
                objectUri: objectUri,
                objectType: objectType,
                displayName: displayName,
                name: name,
                iconUrl: iconUrl
            })
            // 当前页面的所有点
            this.allMark.push(marker)
            this.$parent.allMark = this.markerListNew
            google.maps.event.addListener(marker, 'click', e => {
                // marker.setIcon(
                //   new BMap.Icon(eventPointCheckImg, new BMap.Size(32, 36), {
                //     imageOffset: new BMap.Size(0, 0),
                //     imageSize: new BMap.Size(32, 36)
                //   })
                // );
                // marker.setShadow(
                //   new BMap.Icon(eventPointCheckImg, new BMap.Size(0, 0), {})
                // );
                this.current_obj_rowkey = rowkey
                this.current_obj_uri = objectUri
                this.objectInfo = {
                    longitude: lng,
                    latitude: lat,
                    rowkey: rowkey,
                    objectUri: objectUri,
                    objectType: objectType,
                    displayName: displayName,
                    name: name,
                    iconUrl: iconUrl
                }
                // 当前被点击的标注
                this.current_checked_marker = this.objectInfo
                this.$parent.current_checked_marker = rowkey
                this.$parent.showInfo(event, -1, this.objectInfo)
                // 其他marker的恢复原样
                // for (let item of this.allMark) {
                //   if (item.customData && item.customData.rowkey !== rowkey) {
                //     item.setIcon(
                //       new BMap.Icon(eventPointImg, new BMap.Size(23, 25), {
                //         imageOffset: new BMap.Size(0, 0),
                //         imageSize: new BMap.Size(23, 25)
                //       })
                //     );
                //   }
                // }
            })
            google.maps.event.addListener(marker, 'rightclick', e => {
                //    删除当前marker
                this.CurrentDelmarker = {
                    marker: marker,
                    rowkey: rowkey,
                    objectUri: objectUri
                }
                if (window.event) {
                    e = window.event
                    e.stopPropagation()
                    e.preventDefault()
                }
                this.MarkmenuShow = true
                if (this.MarkmenuShow) {
                    var mymenu = document.getElementById('Markmenu')
                    mymenu.style.left = e.clientX + 5 + 'px'
                    mymenu.style.top = e.clientY - 30 + 'px'
                }
            })
        },
        // 当marker被单击后高亮显示，其他的恢复原样
        // changeMarkerIcon (markerListNew, marker) {
        //     markerListNew.forEach(ele => {
        //         if (!(ele.longitude === marker.longitude && ele.latitude === marker.latitude && ele.rowkey === marker.rowkey)) {
        //             mapUtil.tool.removeMarker(this.map, ele.longitude, ele.latitude)
        //             this.addMarker(ele.longitude, ele.latitude, ele.rowkey, ele.objectUri, ele.objectType, ele.displayName, ele.name, ele.iconUrl)
        //         }
        //     })
        // },
        // 标点删除
        removeMarker () {
            let marker = this.CurrentDelmarker.marker
            for (let [index, item] of this.markerListNew.entries()) {
                if (item.rowkey == marker.customData.rowkey) {
                    this.markerListNew.splice(index, 1)
                    this.map.removeOverlay(marker)
                    return true
                }
            }
        },
        // 添加至该分组
        selecthandleAddGroup () {
            this.handleAddGroup(
                this.CurrentDelmarker.rowkey,
                this.CurrentDelmarker.objectUri
            )
        },
        handleAddGroup (rowkey, objecturi) {
            let addinstanceObj = {
                gid: sessionStorage.getItem('MapgroupId'),
                objs: [
                    {
                        objectUri: objecturi,
                        rowkey: rowkey
                    }
                ]
            }
            addInstance(addinstanceObj)
                .then(res => {
                    if (res.status == 200) {
                        this.$message({
                            message: '添加至该分组成功',
                            type: 'success'
                        })
                        // 跟新分组数据
                        this.$parent.activeBar = 1
                        this.$parent.handleGroupList()
                        // this.nodesVisible = false
                    } else {
                        this.$message({
                            message: '添加至该分组失败',
                            type: 'error'
                        })
                    }
                })
                .catch(error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    })
                })
        },
        // 关闭地图标定对话框
        closeMapCalibrationDialog () {
            this.initStatus()
            this.newMarker.setMap(null)
            this.dialogMapCalibrationVisible = false
        },
        // 关闭选择分组对话框
        closeChooseGroupDialog () {
            this.initStatus()
            this.dialogChooseGroupVisible = false
        },
        // 根据绘制类型查询
        searchByDrawType (objectList, propertyList, queryTimeStart, queryTimeEnd) {
            propertyList = propertyList.map(item => {
                return {
                    propertyUri: item,
                    propertyType: 'GisData'
                }
            })
            switch (this.drawType) {
            case 'circle':
                this.searchByClircle(
                    objectList,
                    propertyList,
                    queryTimeStart,
                    queryTimeEnd
                )
                break
            default:
                this.searchByPolygon(
                    objectList,
                    propertyList,
                    queryTimeStart,
                    queryTimeEnd
                )
            }
        },
        // 圆形区域搜索
        searchByClircle (objectList, propertyList, queryTimeStart, queryTimeEnd) {
            // 请求参数
            let params = {
                gisShape: 'CIRCLE',
                circle: {
                    latitude: this.centerPoint.lat,
                    longitude: this.centerPoint.lng,
                    distance: Number(this.radius)
                },
                objectList: objectList,
                propertyList: propertyList,
                queryTimeStart: new Date(queryTimeStart).getTime(),
                queryTimeEnd: new Date(queryTimeEnd).getTime()
            }
            getGisList(params).then(response => {
                this.objectList = response.data
                this.objectList.forEach(item => {
                    this.addMarker(
                        item.longitude,
                        item.latitude,
                        item.rowkey,
                        item.objectUri,
                        item.objectType,
                        item.displayName,
                        item.name,
                        item.iconUrl
                    )
                })
            })
        },
        // 多边形区域搜索(包括矩形，多边形，折线)
        searchByPolygon (objectList, propertyList, queryTimeStart, queryTimeEnd) {
            // 请求参数
            let params = {
                gisShape: 'POLYGON',
                polygon: this.pointArr,
                objectList: objectList,
                propertyList: propertyList,
                queryTimeStart: new Date(queryTimeStart).getTime(),
                queryTimeEnd: new Date(queryTimeEnd).getTime()
            }
            getGisList(params).then(response => {
                this.objectList = response.data
                this.objectList.forEach(item => {
                    this.addMarker(
                        item.longitude,
                        item.latitude,
                        item.rowkey,
                        item.objectUri,
                        item.objectType,
                        item.displayName,
                        item.name,
                        item.iconUrl
                    )
                })
            })
        },
        getlintnewpoint (pointarr) {
            this.map.setViewport(pointarr, {
                enableAnimation: false,
                margins: [5, 5, 5, 5]
            })
            let pointarrb = []
            // 将所有的点放置在最佳视野内
            let bs = this.map.getBounds() // 获取可视区域
            let bssw = bs.getSouthWest() // 可视区域左下角
            let bsne = bs.getNorthEast() // 可视区域右上角
            let topLat = bsne.lat
            let bottomLat = bssw.lat
            let leftLng = bssw.lng
            let rightLng = bsne.lng
            pointarrb[0] = { longitude: leftLng, latitude: topLat }
            pointarrb[1] = { longitude: leftLng, latitude: bottomLat }
            pointarrb[2] = { longitude: rightLng, latitude: topLat }
            pointarrb[3] = { longitude: rightLng, latitude: bottomLat }
            return pointarrb
        },
        // 清除覆盖物
        clearOverlays () {
            gmapUtil.removeMarkersInMap()
            console.log('allMark', this.allMark)
            gmapUtil.setMapOnAll(null, this.allMark)
            this.markerListNew = []
            this.allMark = []
            this.drawType = ''
        },
        // 清除map所有的事件监听
        removeMapAllListeners () {
            // TODO
            //   this.EventWrapper.clearInstanceListeners(this.map);
        }
    }
}
</script>
<style lang="less">
.toolIcon {
  line-height: 35px;
  background: #ffffff;
  #Markmenu {
    position: absolute;
    z-index: 100000;
    padding: 5px 0;
    border: 1px solid rgba(0, 0, 0, 0.2) !important;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2) !important;
    border-radius: 6px;
    background: #ffffff;
    &.nodata {
      display: none;
    }
    li {
      color: #333 !important;
      padding: 3px 20px !important;
      margin: 0 !important;
      font-weight: 400;
      line-height: 20px;
      white-space: nowrap;
      min-width: 150px;
      cursor: pointer;
      &:hover {
        background: #08c;
        color: #ffffff !important;
      }
    }
  }
  .el-button {
    border: none;
    padding: 7px 15px;
  }
  .saveKz {
    .el-button {
      border: 1px solid #dcdfe6;
      padding: 7px 15px;
    }
  }
}
</style>
<style lang="less">
.main {
  .BMap_contextMenu {
    padding: 5px 0;
    border: 1px solid rgba(0, 0, 0, 0.2) !important;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2) !important;
    border-radius: 6px;
    > div {
      // border-bottom:1px solid#333;
      color: #333 !important;
      padding: 3px 20px !important;
      margin: 0 !important;
      font-weight: normal;
      line-height: 20px;
      white-space: nowrap;
      min-width: 150px;
      &:hover {
        background: #3aa6f0;
        color: #ffffff !important;
      }
    }
  }
}
</style>
